Ext.define('QMS.controller.OrgTree', {
	extend:'Ext.app.Controller',
	models: ['Organisation', 'Unit', 'Project', 'Employee'],
	stores: ['OrgTree'],
	init: function() {
		
		this.addingModel = null;
		this.application.panelModelName = '';

		this.control({
			'*[id^=orgtree]': {
				beforeitemclick: this.onOrgTreeItemClicked
			},
		});

		this.application.on({
			// Context Menu Events
			contextmenuadd: this.onContextMenuAdd,
			contextmenudelete: this.onContextMenuDelete,

			// New Form Submitted Events 
			unitformsubmitted: this.onFormSubmitted,
			projectformsubmitted: this.onFormSubmitted,
			employeeformsubmitted: this.onFormSubmitted,

			// Change Event
			treeelementchanged: this.onTreeElementChanged,

			//debug
			debugreloadtree: this.onDebugReloadTree,
		});
	},

	onContextMenuAdd: function(model) {
		console.log('onContextMenuAdd');
		console.log(model);

		var modelName = model.split('-');
		if (modelName[0] == "ORG") {
			var panel = new QMS.view.Unit({
				title: "Adding new Unit",
				floating: true,
				centered: true,
				modal: true,
				width: 500,
				closable: true,
				id: "add_modal",
				listeners: {
					hide: function(p) {
						p.destroy();
					}
				},
			});
		} else if (modelName[0] == "UNIT") {
			var panel = new QMS.view.Project({
				title: "Adding new Project",
				floating: true,
				centered: true,
				modal: true,
				width: 500,
				closable: true,
				id: "add_modal",
				listeners: {
					hide: function(p) {
						p.destroy();
					}
				},
			});
		} else if (modelName[0] == "PROJ") {
			var panel = new QMS.view.Employee({
				title: "Adding new Employee",
				floating: true,
				centered: true,
				modal: true,
				width: 500,
				closable: true,
				id: "add_modal",
				listeners: {
					hide: function(p) {
						p.destroy();
					}
				},
			});
		} else {
			return;
		}

		panel.show();
		this.addingModel = model;
	},

	// onLaunch: function() {
	// 		var orgTreeStore = this.getOrgTreeStore();
	// 		orgTreeStore.load({
	// 				callback: this.onOrgTreeLoad,
	// 				scope: this
	// 		})
	// },

	// onOrgTreeLoad: function() {
	// 		console.log('onOrgTreeLoad');
	// },

	onContextMenuDelete: function(model) {
		console.log('onContextMenuDelete');
		console.log(model);

		var orgTreeStore = this.getOrgTreeStore();
		orgTreeStore.getNodeById(model).remove();

		orgTreeStore.sync({
			callback: function(batch, options) {
				console.log('callback');
				console.log(batch);
				console.log(options);
			},
			success: function(batch, options) {
				console.log('success');
				console.log(batch);
				console.log(options);
			},
			failure: function(batch, options) {
				Ext.Msg.alert('Failure', 'Failed to remove.');
			},
			scope: this,
		});

		// if panel displays that object then need to close the panel
		if (this.panelModelName == model) {
			var panel = new Ext.panel.Panel({
				xtype: 'panel',
				title: 'Select an item from tree to view it',
				flex: 1,
			})
			var contentView = Ext.ComponentQuery.query('*[id^=content-view]')[0];
			contentView.removeAll(true);
			contentView.add(panel);
		}
	},

	onOrgTreeItemClicked: function(OrgTree, td, cellIndex, record, tr, rowIndex, e, eOpts) {
		console.log('onOrgTreeItemClicked');
		this.application.panelModelName = td.internalId;

		var modelName = td.internalId.split('-');
		if (modelName[0] == "ORG") {
			var panel = new QMS.view.Organisation();
			var fullModelName = 'QMS.model.Organisation';
		} else if (modelName[0] == "UNIT") {
			var panel = new QMS.view.Unit();
			var fullModelName = 'QMS.model.Unit';
		} else if (modelName[0] == "PROJ") {
			var panel = new QMS.view.Project();
			var fullModelName = 'QMS.model.Project'
		} else if (modelName[0] == "EMPL") {
			var panel = new QMS.view.Employee();
			var fullModelName = 'QMS.model.Employee'
		}

		var contentView = Ext.ComponentQuery.query('*[id^=content-view]')[0];
		contentView.removeAll(true);
		contentView.add(panel);

		contentView.setLoading(true);
		var Model = Ext.ModelManager.getModel(fullModelName);
		Model.load(parseInt(modelName[1]), {
			success: function(record) {
				contentView.setLoading(false);
				panel.loadRecord(record);
			}
		});
	},

	onFormSubmitted: function (record) {
		var panel = Ext.ComponentQuery.query('*[id^=add_modal]')[0];
		panel.hide();

		var orgTreeStore = this.getOrgTreeStore();
		var parentNode = orgTreeStore.getNodeById(this.addingModel);

		if (!parentNode.isExpanded()) {
			parentNode.expand()
		}

		var newNode = parentNode.appendChild(record);
		orgTreeStore.sync({

			callback: function(batch, options) {
				console.log('callback');
				console.log(batch);
				console.log(options);
			},
			success: function(batch, options) {
				console.log('success');
				console.log(batch);
				console.log(options);
			},
			failure: function(batch, options) {
				Ext.Msg.alert('Failure', 'Failed to remove.');
			},
			scope: this,

		});
	},

	onTreeElementChanged: function (elemenetId, name) {
		var orgTreeStore = this.getOrgTreeStore();
		orgTreeStore.reload();
	},

	onDebugReloadTree: function () {
		var orgTreeStore = this.getOrgTreeStore();
		orgTreeStore.reload();
	}
});